<template>
  <div>
    <el-card class="swiper-container">
      <template #header>
        <div class="header">
          <el-button
              type="primary"
              @click="handleAdd"
              size="small"
              icon="Plus"
          >增加</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">批量删除</el-button>
            </template>
          </el-popconfirm>
          <span class="parts-text">首页耳机配件商品展示管理</span>
        </div>
      </template>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column
          prop="parts_id"
          label="排序值"
          width="120"
        ></el-table-column>
        <el-table-column
            prop="title"
            label="商品名称"
        ></el-table-column>
        <el-table-column
            prop="price"
            label="商品价格"
        ></el-table-column>
        <el-table-column label="缩略图" width="140">
          <template #default="scope">
            <img
              width="116"
              :src="scope.row.src"
              alt="缩略图"
            />
          </template>
        </el-table-column>
        <el-table-column
            prop="url"
            label="商品编号"
        ></el-table-column>
        <el-table-column label="是否展示">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isShow"
              @change="changeShow(scope.row.isShow, scope.row.parts_id)"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="atime"
          label="添加时间"
          width="165"
        ></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                type="primary"
                @click="handleEdit(scope.row)"
            >修改</el-button>
            <el-button
                type="danger"
                @click="openElMessageBox(scope.row.parts_id)"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--总数超过一页，再展示分页器-->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="changePage"
      />
    </el-card>
    <DialogParts
      ref="changeParts"
      :type="type"
      @changeTableData="changeData"
    />
  </div>
</template>

<script setup>
import DialogParts from "../components/DialogParts.vue";
import { onMounted, reactive, ref, toRefs, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { timeTrans, strSlice } from "../../utils";
import { getParts, deleteParts, showParts, batchDelete } from "../../api/parts";

// 在setup中拿到this，，proxy相当于this
const { proxy } = getCurrentInstance();
const multipleTable = ref(null);
const changeParts = ref();
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  type: "add", // 操作类型
});

let {
  loading,
  tableData,
  multipleSelection,
  total,
  currentPage,
  pageSize,
  type,
} = toRefs(state);

onMounted(async () => {
  // 获取轮播图列表
  const parts = await getParts(proxy);
  parts.forEach((item) => {
    // 处理是否展示图片
    item.isShow = item.isShow === 1;
    // 处理时间
    item.atime = timeTrans(item.atime);
    // 处理商品编号
    item.url = strSlice(item.url);
  });
  state.tableData = parts;
});
// 子传父
const changeData = (data) => {
  data.forEach((item) => {
    // 处理是否展示图片
    item.isShow = item.isShow === 1;
    // 处理时间
    item.atime = timeTrans(item.atime);
    // 处理商品编号
    item.url = strSlice(item.url);
  });
  state.tableData = data;
};

// 是否展示图片
const changeShow = (isShow, parts_id) => {
  // console.log("触发", isShow, parts_id);
  showParts(proxy, { isShow, parts_id }).then((data) => {
    if (data.code === 200) {
      // 提示
      ElMessage({
        type: "success",
        message: "更改成功",
      });
    }
  });
};

// 添加轮播图片
const handleAdd = () => {
  state.type = "add";
  changeParts.value.open();
};
// 修改轮播图片
const handleEdit = (parts) => {
  state.type = "edit";
  changeParts.value.open(parts);
};
// 选择项
const handleSelectionChange = (val) => {
  state.multipleSelection = val;
};
// 批量删除
const handleDelete = () => {
  if (!state.multipleSelection.length) {
    ElMessage.error("请选择项");
  }else {
    let arr = [];
    state.multipleSelection.forEach(item => {
      arr.push(item.parts_id);
    })
    batchDelete(proxy,{arr}).then((data) => {
      if (data.code === 200) {
        // 更新数据，再发一次请求explain
        getParts(proxy).then((result) => {
          result.forEach(item => {
            // 处理是否展示图片
            item.isShow = item.isShow === 1;
            // 处理时间
            item.atime = timeTrans(item.atime);
            // 处理商品编号
            item.url = strSlice(item.url);
          });
          state.tableData = result;
        });
        // 提示
        ElMessage({
          type: "success",
          message: data.msg,
        });
      }else {
        ElMessage({
          type: "error",
          message: data.msg,
        });
      }
    });
  }
};

// 分页
const changePage = async (val) => {
  state.currentPage = val;
};

// 点击删除弹窗
const openElMessageBox = (parts_id) => {
  ElMessageBox.confirm("是否删除当前这条展示商品", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 发送请求删除
      // console.log(id);
      deleteParts(proxy, { parts_id }).then((data) => {
        // console.log(data);
        if (data.code === 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        }
        // 更新数据，再发一次请求parts
        getParts(proxy).then((result) => {
          result.forEach((item) => {
            // 处理是否展示图片
            item.isShow = item.isShow === 1;
            // 处理时间
            item.atime = timeTrans(item.atime);
            // 处理商品编号
            item.url = strSlice(item.url);
          });
          state.tableData = result;
        });
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
</script>

<style scoped>
.swiper-container {
  min-height: 100%;
}
.el-card.is-always-shadow {
  min-height: 100% !important;
}
.parts-text {
  display: inline-block;
  position: relative;
  top: 1px;
  font-weight: bold;
  font-size: 16px;
  margin-left: 20px;
}
</style>
